﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMOShared;
using System.IO;
using System.Windows.Forms;

namespace MMOShared
{
    public class MasterVersionList
    {
        public Dictionary<UInt16, ResourceManager> ResourceVersions { get; private set; }
        public UInt16 LatestVersion { get; private set; }

        public MasterVersionList()
        {
            ResourceVersions = new Dictionary<ushort, ResourceManager>();
            LatestVersion = 0;
        }

        public void ScanDirectory(string dirPath)
        {
            DirectoryInfo di = new DirectoryInfo(dirPath);
            DirectoryInfo[] subDirs = di.GetDirectories();
            foreach (DirectoryInfo subDir in subDirs)
            {
                if (subDir.Name[0] != '.')
                {
                    UInt16 version;
                    try
                    {
                        version = UInt16.Parse(subDir.Name);
                    }
                    catch (FormatException e)
                    {
                        MessageBox.Show("Error: found a directory, " + subDir.Name + " not containing a version");
                        return;
                    }
                    ResourceManager newVer = ResourceManager.Load(Path.Combine(subDir.FullName, Path.Combine("..\\","res_man_"+subDir.Name+".res")));
                    
                    if (newVer.IsLoaded)
                    {
                        LatestVersion++;
                        ResourceVersions.Add(version, newVer);
                    }
                    else
                    {
                        MessageBox.Show("Directory " + subDir.Name + " was not added because it is missing a resource list");
                    }
                }
            }
        }

        public void AddNewVersion(ResourceManager res)
        {
            LatestVersion++;
            ResourceVersions.Add(LatestVersion, res);
        }

        public ResourceManager GetVersion(UInt16 ver){
            if(ResourceVersions.ContainsKey(ver)){
                return ResourceVersions[ver];
            }
            return null;
        }

        public UInt16[] GetLoadedVersionNumbers()
        {
            return ResourceVersions.Keys.ToArray();
        }

    }
}
